package com.gds.wiki.cloud.orderCenter.server.oauth2.config;

import com.gds.wiki.cloud.framework.web.constant.HttpSecurityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;


@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    RedisTokenStore redisTokenStore;

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(HttpSecurityConstant.swagger_ui_matchers()).permitAll()
                .antMatchers(HttpSecurityConstant.user_white_list()).permitAll()
//                .antMatchers("/oauth2/token").permitAll()
                .anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {


        resources.resourceId("member").stateless(true)
                .tokenStore(redisTokenStore)
                .authenticationEntryPoint(new RestAuthenticationEntryPoint());
        ;

    }


    @Bean // 声明 ClientDetails实现
    public ClientDetailsService clientDetails() {
        return new InMemoryClientDetailsService();
    }

    //设置header 存放token
    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(){
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(redisTokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

}
